package org.funtester.performance.books.chapter06.section3;

import org.funtester.performance.books.chapter03.section3.ThreadTask;
import org.funtester.performance.books.chapter03.section4.TaskExecutor;
import org.funtester.performance.books.chapter04.section3.RandomTool;
import org.funtester.performance.books.chapter06.section2.MySqlBase;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 插入数据,多线程并发,批量插入多行
 */
public class InsertData {

    public static void main(String[] args) throws SQLException, InterruptedException {
        String valueFrormat = "('%s', %d, %d, '%s', '%s')";
        String url = "jdbc:mysql://127.0.0.1:3306/funtester";// 服务端地址
        String user = "root";// 用户名
        String password = "funtester";// 密码
        List<ThreadTask> tasks = new ArrayList<>();// 任务集合
        for (int i = 0; i < 10; i++) {
            ThreadTask threadTask = new ThreadTask() {

                MySqlBase base = new MySqlBase(url, user, password);// 创建数据库操作基础类


                @Override
                public void before() {
                    super.before();
                    base = new MySqlBase(url, user, password);// 创建数据库操作基础类
                    try {
                        base.init();// 初始化资源
                    } catch (SQLException e) {
                        throw new RuntimeException(e);
                    }
                }

                @Override
                public void test() {
                    StringBuilder sqlFormat = new StringBuilder("insert into user (name, age, level, region, address) values ");// SQL 语句前缀
                    for (int j = 0; j < 10; j++) {// 每次插入10条数据
                        String name = RandomTool.getRandomString(32);// 随机生成姓名
                        int age = ThreadLocalRandom.current().nextInt(100);// 随机生成年龄
                        int level = ThreadLocalRandom.current().nextInt(10);// 随机生成等级
                        String region = RandomTool.getRandomString(32);// 随机生成地区
                        String address = RandomTool.getRandomString(512);// 随机生成地址
                        String value = String.format(valueFrormat, name, age, level, region, address);// 格式化值
                        sqlFormat.append(value).append(",");// 拼接值
                    }
                    sqlFormat.deleteCharAt(sqlFormat.length() - 1);// 删除最后一个逗号
                    try {
                        base.statement.executeUpdate(sqlFormat.toString() + ";");// 执行插入语句
                    } catch (SQLException e) {
                        throw new RuntimeException(e);
                    }
                }
            };
            threadTask.totalNum = 1000;// 设置执行次数
            threadTask.costTime = new ArrayList<>(1000);// 设置任务的执行时间集合,设置容量,避免频繁扩容
            tasks.add(threadTask);// 添加任务
        }
        TaskExecutor taskExecutor = new TaskExecutor(tasks, "并发批量写入多行",10);
        taskExecutor.start();// 启动任务执行器
    }


}
